/**
 * @author xiaowei
 * @date 2017年4月25日
 */
Ext.define('App.view.common.Toolbar', {
    extend: 'Ext.form.Panel',
    mixins: ['App.view.common.CommonFun'],
    xtype: 'commontoolbar',
    border: false,
    layout: 'hbox',
    height: 35,
    //height: 45,//touch模式
    bodyStyle: {
        background: '#f5f5f5'
    },
    defaults: {
        margin: '6 3 5 3'
    },
    _mainConfs: [/*
	 {name: 'name',type: 'string',text: '姓名'},
	 {name: 'age',text: '年龄'},
	 {name: 'email',type: 'string',text: '邮箱'},
	 {name: 'date',type: 'date',text: '日期'}*/
    ],
    autoPrompt: true,//操作成功是否自动弹出浮框提示，默认true提示
    _targetObject: '',//执行参数操作的对象
    _confs: {
        //components:[{name: 'c',text: '新增检验批',url:''},'s','u','d','export']
    },

    initComponent: function () {
        this.items = this._getComponents();

        this.callParent();
    },
    _getComponents: function () {
        if (!this._confs || !this._confs.components) {
            this.hidden = true;
            return;
        }

        var component, temp, components = [],
            bts = this._confs.components,
            i, confObj;

        for (i = 0; i < bts.length; i++) {
            confObj = bts[i];
            if (Ext.isString(confObj)) {//如果是字符串
                //生成对应的操作按钮
                component = this._getComponentByName(confObj);
                if (component) {
                    components.push(component);
                }
            } else if (Ext.isObject(confObj)) {//如果是对象

                component = this._getComponentByObject(confObj);
                components.push(component);
            }
        }

        return components;
    },
    _getComponentByObject: function (obj) {
        var component = this._getComponentByName(obj.name);
        if (!obj.offAuto && component) {//是否自动生成开关，默认开启
            Ext.applyIf(obj, component);
        }
        Ext.applyIf(obj, {xtype: 'button'});
        return obj;
    },

    _getComponentByName: function (obj) {
        var button, url = '';
        var ftgPanel = this.ftgPanel;
        if (ftgPanel) {
            url = this._getBaseUrl(ftgPanel);
        }
        switch (obj) {
            case 'c': //新增
                button = {
                    tooltip: '新增',
                    xtype: 'button',
                    name: obj,
                    iconCls: 'x-fa fa-plus',
                    handler: this._create,
                    actionUrl: url ? url + '/add' : '',
                    bind: {
                        hidden: '{add}'
                    }
                };
                break;
            case 's': //查询
                button = {
                    xtype: 'button',
                    name: obj,
                    tooltip: '查询',
                    iconCls: "x-fa fa-search fa-lg",
                    handler: this._search,
                    cusType:'search',
                    bind: {
                        hidden: '{search}'
                    }
                };
                break;
            case 'refresh': //查询
                button = {
                    xtype: 'button',
                    name: obj,
                    tooltip: '刷新',
                    iconCls: "x-fa fa-refresh fa-lg",
                    handler: this._refresh,
                    cusType:'search',
                    bind: {
                        hidden: '{refresh}'
                    }
                };
                break;
            case 'u': //更新
                button = {
                    xtype: 'button',
                    name: obj,
                    tooltip: '编辑',
                    iconCls: 'x-fa fa-pencil',
                    isMultiSelect: false,
                    handler: this._update,
                    actionUrl: url ? url + '/update' : '',
                    cusType:'edit',
                    bind: {
                        hidden: '{update}'
                    }
                };
                break;
            case 'd': //删除
                button = {
                    xtype: 'button',
                    name: obj,
                    tooltip: '删除',
                    iconCls: 'x-fa fa-remove',
                    handler: this._delete,
                    actionUrl: url ? url + '/del' : '',
                    cusType:'del',
                    bind: {
                        hidden: '{del}'
                    }
                };
                break;
            case 'export': //导出
                button = {
                    xtype: 'button',
                    name: obj,
                    tooltip: '导出',
                    text: '导出',
                    iconCls: 'x-fa fa-cloud-download',
                    handler: this._export,
                    bind: {
                        hidden: '{export}'
                    }
                };
                break;
            case 'import': //导入
                button = {
                    xtype: 'button',
                    name: obj,
                    tooltip: '导入',
                    text: '导入',
                    iconCls: 'x-fa fa-upload',
                    handler: this._import,
                    bind: {
                        hidden: '{import}'
                    }
                };
                break;
            case 'print': //导入
                button = {
                    xtype: 'button',
                    name: obj,
                    tooltip: '打印',
                    text: '打印',
                    iconCls: 'x-fa fa-print',
                    handler: this._print,
                    bind: {
                        hidden: '{print}'
                    }
                };
                break;
            case 'r': //重置
                button = {
                    xtype: 'button',
                    tooltip: "重置",
                    name: 'r',
                    iconCls: "x-fa fa-undo",
                    handler: this._reset
                };
                break;
            case 'copy': //复制新建
                button = {
                    xtype: 'button',
                    name: obj,
                    tooltip: '复制新建',
                    text: '复制新建',
                    iconCls: "x-fa fa-copy",
                    actionUrl: url ? url + '/add' : '',
                    handler: this._copy,
                    bind: {
                        hidden: '{copy}'
                    }
                };
                break;
            case 'set':
                button = {
                    tooltip: '设置',
                    xtype: 'button',
                    name: obj,
                    iconCls: 'x-fa fa-plus-square',
                    handler: this._create,
                    actionUrl: url ? url + '/add' : '',
                    bind: {
                        hidden: '{set}'
                    }
                };
                break;
            case 'more':
                button = {
                    tooltip: '更多信息',
                    xtype: 'button',
                    name: obj,
                    moreType:true,
                    iconCls: 'x-fa fa-angle-double-right',
                    handler: this._more,
                    bind: {
                        hidden: '{set}'
                    }
                };
                break;
        }
        return button;
    },

    //如果没有item显示，隐藏自己
    _isHideMyself: function () {
        var buttons = this.query('button');
        var flag = true;
        for (var i = 0; i < buttons.length; i++) {
            if (!buttons[i].hidden && flag) {
                this.show();
                flag = false;
            } else if (buttons[i].hidden) {
                //this.remove(buttons[i]);
            }
        }
    },

    _search: function (btn) {
        if (App && App.Application && App.Application.forbidRepeatClick) {
            App.Application.forbidRepeatClick(btn);
        }
        var toolbar = btn.up('commontoolbar')
            , form = toolbar.down('form')
            , crudGrid = toolbar._targetObject
            , params
        ;

        if (form) {
            params = form.getForm().getValues();
            crudGrid._search(params);
        } else {
            crudGrid._search();
        }
    },

    _refresh: function (btn) {
        if (App && App.Application && App.Application.forbidRepeatClick) {
            App.Application.forbidRepeatClick(btn);
        }
        var toolbar = btn.up('commontoolbar'),
            grid = toolbar._targetObject;

        grid._refresh();
    },

    _reset: function (btn) {
        if (App && App.Application && App.Application.forbidRepeatClick) {
            App.Application.forbidRepeatClick(btn);
        }
        var toolbar = btn.up('commontoolbar')
            , form = toolbar.down('form')
            , grid = toolbar._targetObject
        ;

        if (form) {
            form.reset();
            grid._search(form.getForm().getValues());
        }
    },

    _create: function (btn) {
        if (App && App.Application && App.Application.forbidRepeatClick) {
            App.Application.forbidRepeatClick(btn);
        }
        var me = btn.up('commontoolbar');
        var win = me._getWindow(btn);
        if (win._show) {
            win._show();
        }
        return win;
    },
    _delete: function (btn) {
        if (App && App.Application && App.Application.forbidRepeatClick) {
            App.Application.forbidRepeatClick(btn);
        }
        //拿到列表选中数据
        var me = btn.up('commontoolbar'),
            params = me._deleteValid(btn),
            text = btn.text,
            url = btn.actionUrl;
        if (!text) {
            text = '操作';
        }
        if (!params) {
            return;
        }

        Ext.MessageBox.confirm(text + '确认', '共选中<span style="color:red;">' + params.length + '</span>行！</br>您确认要' + text + '选中的数据吗?', function (btn) {
            if (btn == 'yes') {
                //父节判断
                App.ux.Ajax.request({
                    url: url,
                    params: {
                        ids: params.toString()
                    },

                    success: function (obj) {
                        me._deleteSuccess(btn);
                    },
                    failure: function () {
                    }
                });

            }
        });

    },

    /**
     * 删除方法的验证逻辑
     * @param btn
     * @returns {*}
     * @private
     */
    _deleteValid: function (btn) {
        var params = this._targetObject._getSelectionDataIds();
        //ajax请求删除数据
        if (!params || params.length < 1) {
            App.ux.Toast.show('提示', '请选中需要操作的行！ <span style="color:red;">*</span>支持多行','i');
            return false;
        }
        return params;
    },
    _update: function (btn) {
        if (App && App.Application && App.Application.forbidRepeatClick) {
            App.Application.forbidRepeatClick(btn);
        }
        var me = btn.up('commontoolbar');
        var grid = me._targetObject,
            select, data, win;

        select = grid.getSelectionModel().getSelection();

        data = me._updateValid(btn, select);

        if (!data) {
            return;
        }
        win = me._getWindow(btn, data);
        // win.isGetChangeValue = true;
        win._show();
        return win;
    },
    /**
     * 复制待办链接方法的验证逻辑
     * 验证成功返回数据对象，验证失败返回false
     * @param btn
     * @param select
     * @returns {Object}
     * @private
     */
    _updateValid: function (btn, select) {
        var title = btn.text;
        if(!title){
            title = btn.tooltip;
        }
        if(!title){
            title = '操作';
        }
        if (!select || select.length < 1) {
            App.ux.Toast.show('提示', '请选择1条需要' + title + '的行','i');
            return false;
        }
        if (!btn.isMultiSelect && select.length > 1) {
            App.ux.Toast.show('提示', '<span style="color:red;">*</span>只能操作一条数据！','i');
            return false;
        }
        return select[0].data;
    },
    _import:function (button) {
        if(!button.actionUrl){
            throw "import导入按钮必须配置导入数据的提交地址actionUrl属性; 示例： actionUrl:'user/importExcel'"
        }
        var me = button.up('commontoolbar');
        Ext.create('App.view.common.WindowImport',{
            _targetObject:me._targetObject,
            _confs:{
                url: button.actionUrl
            }
        }).show();
    },
    _export: function (button) {
        var exportUrl = URLPreName + button.actionUrl;
        var me = button.up('commontoolbar');
        //查询条件
        var grid = me._targetObject;
        var gridStroe = grid.getStore(), extraParams = gridStroe.getProxy().extraParams;
        exportUrl += "?1=1";
        if (extraParams) {
            for (var key in extraParams) {
                exportUrl += "&" + key + extraParams[key];
            }
        }
        window.location.href = encodeURI(exportUrl);
        App.ux.Toast.show('提示',"数据导出中，请留意正在下载文件",'i');

    },
    _print:function (btn) {
        this.up('commontoolbar')._update(btn);
    },
    _deleteSuccess: function (btn) {
        var grid = this._targetObject;
        var text = '操作';
        if (btn && btn.text) {
            text = btn.text;
        }
        if (this.autoPrompt) {
            App.ux.Toast.show('提示', text + '成功！','s');
        }
        grid._searchPage();
    },

    _copy: function (btn) {
        if (App && App.Application && App.Application.forbidRepeatClick) {
            App.Application.forbidRepeatClick(btn);
        }
        var me = btn.up('commontoolbar');
        var grid = me._targetObject,
            select, data, win;

        select = grid.getSelectionModel().getSelection();
        if (!select || select.length < 1) {
            App.ux.Toast.show('提示', '请选中需要' + btn.text + '的行！ <span style="color:red;">*</span>只支持单行','i');
            return;
        }
        if (!btn.isMultiSelect && select.length > 1) {
            App.ux.Toast.show('提示', btn.tooltip + '功能 <span style="color:red;">*</span>只支持单行','i');
            return;
        }
        data = Ext.apply({}, select[0].data);
        win = me._getWindow(btn, data);
        win.clearIdField();
        win._show();
    },

    _getWindow: function (btn, record) {
        var me = this;
        var winConfigs = {
            header: {
                title: btn.text ? btn.text : btn.tooltip
                //iconCls: btn.iconCls
            },
            openValidation: true,
            _toolbar: this,
            _trigger: btn,
            _record: record,
            _targetObject: me._targetObject,
            _confsOveride: {
                url: btn.actionUrl,
                dataMapping: me._mainConfs
            },
            xtype: btn.actionObject ? btn.actionObject : 'commonwindow'
        };
        if (Ext.isObject(btn.actionObject)) {
            winConfigs = Ext.applyIf(Ext.clone(btn.actionObject), winConfigs);
        }
        var win = Ext.create(winConfigs);
        return win;
    },

    _getViewWindow: function (btn, record) {
        var winConfigs = {
            header: {
                title: btn.text ? btn.text : btn.tooltip
                // iconCls: btn.iconCls ? btn.iconCls : 'fa fa-eye'
            },
            _toolbar: this,
            _trigger: btn,
            _isView: true,
            _record: record,
            _targetObject: this._targetObject,
            _confsOveride: {
                url: btn.actionUrl,
                dataMapping: this._mainConfs
            },
            xtype: btn.actionObject ? btn.actionObject : 'commonwindow'
        };
        if (Ext.isObject(btn.actionObject)) {
            winConfigs = Ext.applyIf(Ext.clone(btn.actionObject), winConfigs);
        }
        var win = Ext.create(winConfigs);
        return win;
    },
    enableOrDisableBtns:function (names) {
        if(!names){
            return;
        }
        var btn;
        for(var k in names){
            btn = this.down('button[name='+k+']');
            if(btn){
                if(names[k]){
                    btn.enable();
                }else {
                    btn.disable();
                }
            }
        }
    },
    _more:function (btn) {
        var me = btn.up('commontoolbar');
        if(btn.moreType){
            btn.moreType = false;
            btn.setTooltip('收起');
            btn.setIconCls('x-fa fa-angle-double-left');
        }else {
            btn.moreType = true;
            btn.setTooltip('更多');
            btn.setIconCls('x-fa fa-angle-double-right');
        }
        me._targetObject.showHideColumn();
    }

});
